package com.diver.flinkdemo.sink;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diver.flinkdemo.constant.UploadCommandKeyConstant;
import com.diver.flinkdemo.entity.DalData;
import com.diver.flinkdemo.entity.xxt.*;
import com.diver.flinkdemo.mapper.dorisMapper.IssuedPermissionRecordMapper;
import com.diver.flinkdemo.mapper.dorisMapper.StudentCardParamsMapper;
import com.diver.flinkdemo.mapper.mysqlMapper.MessageSendMapper;
import com.diver.flinkdemo.mapper.mysqlMapper.MoreSettingMapper;
import com.diver.flinkdemo.mapper.mysqlMapper.TerminalUnitMapper;
import com.diver.flinkdemo.readervo.TemplateParamsDefinition;
import com.diver.flinkdemo.readervo.TerminalTemplate;
import com.diver.flinkdemo.utils.DynamicDataSourceUtil;
import com.diver.flinkdemo.utils.TemplateFileReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.Date;

/**
 * @author LuJW
 * @date 2023/3/29 10:56
 */
@Slf4j
public class IssuedPermissionRecordSink extends RichSinkFunction<DalData> {
    /**
     * sqlSessionFactory
     */
    private SqlSessionFactory sqlSessionFactory;
    private SqlSessionFactory mysqlSqlSessionFactory;
    private final IssuedPermissionRecord permissionRecord = new IssuedPermissionRecord();
    private TerminalTemplate template;

    @Override
    public void open(Configuration parameters) throws Exception {
//        log.info("DataSourceFactoryUtil->{}",DataSourceFactoryUtil);
        if (DynamicDataSourceUtil.dorisSessionFactory == null) {
            DynamicDataSourceUtil sourceUtil = new DynamicDataSourceUtil();
            sourceUtil.init();
            log.info("二次初始化完成...");
        }
        log.info("初始化获取sqlSessionFactory->{}", DynamicDataSourceUtil.dorisSessionFactory);
        sqlSessionFactory = DynamicDataSourceUtil.dorisSessionFactory;
        mysqlSqlSessionFactory = DynamicDataSourceUtil.mysqlSessionFactory;
        TemplateFileReader.loadTemplateByNACOS();
    }

    @Override
    public void invoke(DalData value, Context context) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        SqlSession mysqlSession = mysqlSqlSessionFactory.openSession(true);

        try {
            //获取sqlSession
            if (value !=null) {
                //IssuedPermissionRecord 指令下发状态修改
                IssueCommandCallBackHandle(value,sqlSession,mysqlSession);

            }
        } catch (Exception e) {
            log.error(this.getClass().getName() + ".invoke()执行失败", e);
            //重试一次
            try {
                if (sqlSession != null) {
//                    sqlSession.getMapper(TestMapper.class).batchSave(values);
//                    sqlSession.getMapper(IssuedPermissionRecordMapper.class).insert(value);
                    IssueCommandCallBackHandle(value,sqlSession,mysqlSession);
                }
            } catch (Exception ex) {
                log.error(this.getClass().getName() + ".invoke()重试执行失败", e);
            }
        } finally {
            //关闭sqlSession
            if (sqlSession != null) {
                log.info("session commit -> session close");
                DynamicDataSourceUtil.sessionDoAfter(sqlSession);
            }
        }
    }

    public void IssueCommandCallBackHandle(DalData dalData, SqlSession sqlSession,SqlSession mysqlSession) {
        if ("execute".equals(dalData.getStatus())) {
            log.info("执行中");
            return;
        }
        log.info("sqlSessionFactory->{}",sqlSessionFactory);
        IssuedPermissionRecordMapper permissionRecordMapper= sqlSession.getMapper(IssuedPermissionRecordMapper.class);
        StudentCardParamsMapper studentCardParamsMapper = sqlSession.getMapper(StudentCardParamsMapper.class);
        MoreSettingMapper moreSettingMapper = mysqlSession.getMapper(MoreSettingMapper.class);
        TerminalUnitMapper terminalUnitMapper = mysqlSession.getMapper(TerminalUnitMapper.class);
        MessageSendMapper messageSendMapper = mysqlSession.getMapper(MessageSendMapper.class);

        log.info("指令回复，tag：{}",dalData.getTag());
        String tag = dalData.getTag();
        if (StringUtils.isNotBlank(tag)) {
            permissionRecord.setTagId(tag);
            IssuedPermissionRecord issuedPermissionRecord = permissionRecordMapper.selectById(tag);
            if (issuedPermissionRecord == null) {
                log.info("未找到对应的issuedPermissionRecord数据，tag：{}",tag);
                return;
            }
            String deviceId = issuedPermissionRecord.getDeviceId();
            if ("success".equals(dalData.getStatus())) {
                permissionRecord.setSendStatus(1);
                permissionRecord.setUpdateTime(new Date());

            }else if ("fail".equals(dalData.getStatus()) || "expired".equals(dalData.getStatus())) {
                //下发指令执行失败或指令失效
                permissionRecord.setSendStatus(0);
                permissionRecord.setUpdateTime(new Date());
            }
            //应用管理指令执行结果上报
            if (UploadCommandKeyConstant.APPMAN.equals(dalData.getTypeIdent())) {
                //根据deviceId获取StudentCardParams
                StudentCardParams studentCardParams = studentCardParamsMapper.selectById(deviceId);
                //下发的应用开关，1：开启；1：关闭
                Integer appIsOpen = studentCardParams.getAppIsOpen();
                //下发的应用类型
                Integer appIdType = studentCardParams.getAppIdType();

                QueryWrapper<MoreSetting> qw = new QueryWrapper<>();
                qw.eq("card_num",deviceId);
                qw.eq("del_flag","0");
                MoreSetting moreSetting = moreSettingMapper.selectOne(qw);
                //mosettings中的应用状态（闹钟，通话记录，短信代收，消息发送）应用状态（0：未开启 1：已开启 2：卸载中 3：安装中）
                Integer statuss = 0;
                //下发指令执行成功
                if ("success".equals(dalData.getStatus())) {
                    //指令执行成功时，可以直接赋值
                    statuss = appIsOpen;

                }
                switch (appIdType) {
                    //闹钟
                    case 1:
                        moreSetting.setAlarmClockStatus(statuss);
                        break;
                    //消息发送
                    case 2:
                        moreSetting.setMessageSendStatus(statuss);
                        break;
                    //短信代收
                    case 3:
                        moreSetting.setSmsCollectionStatus(statuss);
                        break;
                    //通话记录
                    case 4:
                        moreSetting.setCallRecordStatus(statuss);
                        break;

                }
                //修改studentCardSetting表
                moreSettingMapper.updateById(moreSetting);
                log.info("应用管理指令执行成功，状态同步成功，deviceId:{}",deviceId);
            } else if (UploadCommandKeyConstant.SMSMSG.equals(dalData.getTypeIdent())) {
                //消息发送指令执行结果上报
                MessageSend messageSend = messageSendMapper.getMessageBySmsUid(dalData.getSmsUid());
                if (StringUtils.isNotBlank(dalData.getStatus()) && "success".equals(dalData.getStatus())) {
                    messageSend.setIssuedMsgStatus(1);
                    messageSend.setUpdateTime(new Date());
                } else {
                    messageSend.setIssuedMsgStatus(2);
                    messageSend.setUpdateTime(new Date());
                }
                messageSendMapper.updateById(messageSend);
            }
            //修改IssuedPermissionRecord表
            permissionRecordMapper.insert(permissionRecord);
            log.info("IssuedPermissionRecord save complete!");

            //同步student_card_params
            String[] tagSplitArr = tag.split("_");
            String templateTypeId = tagSplitArr[0];
            String series = terminalUnitMapper.getTerminalSeriesByCardNum(deviceId);
            TemplateParamsDefinition param = TerminalTemplate.getParamById(templateTypeId, series);
            //回调字段
            String callbackStatus = param.getCallbackStatus();
            if (StringUtils.isNotBlank(callbackStatus)) {
                if ("success".equals(dalData.getStatus())) {
                    studentCardParamsMapper.asyncParamFieldByCardNum(callbackStatus,deviceId,2);
                }else if ("fail".equals(dalData.getStatus()) || "expired".equals(dalData.getStatus())){
                    studentCardParamsMapper.asyncParamFieldByCardNum(callbackStatus,deviceId,0);
                }
            }

        }

    }
}
